package com.mc.lp.security.user;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.mc.lp.view.constants.IConstants;
/**
 * @author: deepak.verma
 * @description: handle the request on successful login, it will decide landing page returned by AbstractRedirectStrategy based on user authorities.
 * */
public class SimpleAuthenticationSuccessHandler implements AuthenticationSuccessHandler, IConstants {
	private AbstractRedirectStrategy redirectStrategy;
	
	protected Logger logger = Logger.getLogger(SimpleAuthenticationSuccessHandler.class);
    public void onAuthenticationSuccess(HttpServletRequest request,
      HttpServletResponse response, Authentication authentication) throws IOException {
        handle(request, response, authentication);
        clearAuthenticationAttributes(request);
    }
 
    protected void handle(HttpServletRequest request,
      HttpServletResponse response, Authentication authentication) throws IOException {
        if (response.isCommitted()) {
            logger.debug("Response has already been committed. Unable to redirect :"+authentication.getAuthorities());
            return;
        }
        redirectStrategy.sendRedirect(request, response, authentication);
    }
 
    protected void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    }
 
    public void setRedirectStrategy(AbstractRedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }
    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }

}
